

/*
 * @Autor: Mr Lu
 * @Version: 1.0
 * @Date: 2019-12-03
 * @LastEditors: OBKoro1
 * @LastEditTime: 2019-12-03
 * @Description:  开始测量
  
 */
<template>
  <div id="StartMeasure" class="p-box">
    <div class="p-return" style="margin-bottom:0">
      <mu-appbar color="primary" class="lan-header">
        <mu-button icon slot="left" v-close>
          <i class="iconfont angle-left iconangle-left"></i>
          <span class="lan-header-back">返回</span>
        </mu-button>进行测量
      </mu-appbar>
    </div>
    <div class="p-content" ref="$content">
      <div class="lan-dialog-body" style="background:#fff">
        <mu-form
          ref="form"
          :model="form"
          class="mu-lan-form"
          :label-position="'left'"
          label-width="28%"
        >
          <mu-form-item label="查看详情">
            <mu-text-field
              placeholder="请选择"
              container="bottomSheet"
              :readonly="true"
              label-float
              @click="goDetail"
            ></mu-text-field>
            <i class="iconfont angle-left iconangle-right"></i>
          </mu-form-item>
          <mu-form-item label="责任单位">
            <mu-text-field v-model="form.deptName" container="bottomSheet" :readonly="true"></mu-text-field>
          </mu-form-item>
          <mu-form-item label="实测分项" class="required">
            <mu-select
              v-model="form.subentry"
              placeholder="请选择"
              popover-class="lan-popover-select"
              @change="subChange"
            >
              <mu-option
                v-for="(list,index) in subentryList"
                :key="index"
                :label="list.subentryName"
                :value="list.id"
              ></mu-option>
            </mu-select>
            <i class="iconfont angle-left iconangle-right"></i>
          </mu-form-item>
          <mu-form-item label="平面图标记" class="form-between" style="box-shadow:none">
            <span class="flex ai-center">
              <label style="margin-right:0.05rem">隐藏标号</label>
              <mu-switch v-model="showFlag" @change="FlagChange"></mu-switch>
            </span>
          </mu-form-item>
          <div class="picture-area">
            <div class="map-container">
              <MapShow
                v-if="form.photoUrl"
                ref="MapShow"
                :enableClick="true"
                
                :width="'100%'"
                :currentPointId="nowPointId"
                :url="form.photoUrl"
                v-model="form.pointList"
                :showPoint="showPoint"
                :readonly="true"
                @click="positionClick"
              ></MapShow>
            </div>
            <div class="input-list" v-show="showInputList">
              <div class="input-item" v-for="(f,index) in inputList" :key="index">
                <label>
                  <span>{{f.contentName}}</span>
                  <i class="iconfont iconwenhao" @click.stop="openFileLog(f)"></i>
                </label>
                <mu-text-field
                  type="number"
                  v-show="f.qualifiedType==1"
                  v-model="f.value"
                  container="bottomSheet"
                  :placeholder="f.conVal"
                ></mu-text-field>

                <mu-select
                  v-show="f.qualifiedType==2"
                  v-model="f.value"
                  :placeholder="f.conVal"
                  popover-class="lan-popover-select"
                >
                  <mu-option
                    v-for="(list,index) in selectList"
                    :key="index"
                    :label="list.name"
                    :value="list.id"
                  ></mu-option>
                </mu-select>
              </div>
              <div class="input-item" v-if="inputList.length" style="min-height:0.4rem">
                <span class="flex ai-center flex-1 jc-end">
                  <mu-button small color="primary" @click="savePointMessage()">保存</mu-button>
                </span>
              </div>
            </div>
          </div>
          <div class="tbox-container" v-show="tableList.length">
            <div class="tbox" v-for="(item,index) in tableList" :key="index">
              <div class="tbox-title">实测点位{{item.pIndex}}</div>
              <div class="tbox-content">
                <table class="custom-table" style="border: 1px solid #E0E0E0">
                  <tr>
                    <th style="width: 1.07rem;">实测分项</th>
                    <th style="width: 1.1rem;">实测内容</th>
                    <th style="width: .8rem;">数值</th>
                    <th style="width: .8rem;">结果</th>
                    <th class="config">操作</th>
                  </tr>
                  <tr v-for="(td,tIndex) in item.content" :key="tIndex">
                    <!-- 实测分项 -->
                    <td style="width: 1.07rem;">{{td.subentryName}}</td>
                    <!-- 实测内容 -->
                    <td style="width: 1.1rem;">{{td.contentName}}</td>
                    <!-- 数值 -->
                    <td style="width: .8rem;">{{td.value}}</td>
                    <!-- 结果 -->
                    <td style="width: .8rem;">
                      <span v-if="td.result==1">合格</span>
                      <span v-if="td.result==0">不合格</span>
                    </td>
                    <td class="config">
                      <mu-button small color="error" @click.stop="delTrouble(index,tIndex)">删除</mu-button>
                    </td>
                  </tr>
                </table>
              </div>
            </div>
          </div>
          <mu-form-item label="参与人">
            <mu-text-field v-model="form.joinUser" placeholder="请输入参与人" container="bottomSheet"></mu-text-field>
          </mu-form-item>
          <mu-form-item label="现场照片" class="inline-item" style="padding-bottom:0.15rem;">
            <div v-for="(url,uIndex) in scenePhotosList" :key="uIndex" class="img-box">
              <img :src="url" :preview="uIndex" />
              <mu-icon class="close" value="close" @click.stop="deleteImg(uIndex)"></mu-icon>
            </div>
            <FileUpload @successed="imgSuccess" v-if="scenePhotosList.length < 5"></FileUpload>
          </mu-form-item>
          <!-- <mu-form-item label="抄送至" class="form-between" style="box-shadow:none">
            <mu-text-field
              :placeholder="copyUserList&&copyUserList.length?'已选择'+copyUserList.length:'请选择'"
              container="bottomSheet"
              :readonly="true"
              @click="showSelectUser"
            ></mu-text-field>
          </mu-form-item>
          <div class="copyUserList" v-show="copyUserList.length">
            <mu-chip
              class="demo-chip"
              v-for="(user,uIndex) in copyUserList"
              :key="uIndex"
              @delete="delCopyUser(uIndex)"
              delete
            >{{user.label}}</mu-chip>
          </div>
          -->
          <mu-form-item label="抄送人" class="inline-item hasPadding">
            <div class="userBox" style v-for="(user,uIndex) in copyUserList" :key="uIndex">
              <div
                class="ly_flex ly_flex_just_center ly_flex_ali_center add"
              >{{user.label.substr(0,1)}}</div>
              <span>{{user.label}}</span>
              <i
                class="iconfont iconqingchu"
                @click.stop="delCopyUser(uIndex)"
                style="color: #FF4242;position: absolute;right: .05rem; top: 0;"
              ></i>
            </div>
            <div style @click="showSelectUser">
              <div class="userTrigger">
                <div class="ly_flex ly_flex_just_center ly_flex_ali_center add">
                  <i class="iconfont iconplus"></i>
                </div>
                <span>添加人员</span>
              </div>
            </div>
          </mu-form-item>
        </mu-form>
        <div class="flex" style="padding:0.2rem;box-shadow: 0px -1px 0px 0px #e0e0e0;">
          <div class="flex-1">
            <mu-button full-width color="primary" @click="submit()">提交</mu-button>
          </div>
        </div>
      </div>
    </div>
    <User
      :open="userOpen"
      orgType="currOrgProject"
      data-scope="project-contact"
      :customRoot="userCustomRoot"
      v-model="this.copyUserList"
      @change="userChange"
      @confirm="userConfirm"
      @close="userOpen = false"
    ></User>
    <ImgPreview
      :imgUrls="scenePhotosList"
      :open="showImgPreview"
      @close="showImgPreview=false"
      :slideIndex="imgIndex"
    ></ImgPreview>
    <FilePreview :fileUrl="fileUrl" :open="showFileLog" @close="closeFileDialog" title="示例"></FilePreview>
  </div>
</template>
<script>
import FilePreview from "@/preview/FilePreview.vue";
import ImgPreview from "@/preview/ImgPreview.vue";
import FileUpload from "@/fileUpload/FileUpload.vue";

import User from "@/select/user/User";
import selectArea from "@/realMeasureModule/taskMode/taskModeRealMeasure/selectArea";
export default {
  name: "StartMeasure",
  components: {
    FilePreview,
    ImgPreview,
    FileUpload,
    User
  },
  data() {
    return {
      showImgPreview: false,
      userOpen: false,
      showFlag: false,
      showPoint: true,
      showFileLog: false,
      fileUrl: "",
      openImgPreview: false,
      proUrl: this.$A.baseUrl[0] + "/safety/system/download?fileUrl=",
      form: {
        id: "",
        areaId: "",
        areaName: "",
        deptId: "",
        deptName: "",
        areaName: "",
        photoUrl: "",
        projectId: "",
        projectName: "",
        copyUser: [],
        pointList: []
      },
      userCustomRoot: [
        {
          label: "",
          value: "",
          type: ""
        }
      ],
      imgIndex: 0,
      scenePhotosList: [],
      selectList: [{ name: "合格", id: "1" }, { name: "不合格", id: "0" }],
      showInputList: false,
      nowPointId: "",
      inputList: [],
      unitList: [],
      copyUserList: [],
      subentryList: [],
      currentPointObj: {},
      tableList: []
    };
  },
  watch: {},
  beforeRouteEnter(to, from, next) {
    next(vm => {
      if (
        from.name == "TaskModeAreaList" ||
        from.name == "TaskModeRealMeasure"
      ) {
        vm.$nextTick(() => {
          vm.initForm();
        });
      }
    });
  },
  async created() {
    this.initForm();
  },
  methods: {
    //表单初始化
    initForm() {
      this.clearData();
      this.form = this.$route.query;
      let dataType = typeof this.$route.query.pointList;
      let list =
        dataType == "string"
          ? this.$route.query.pointList
          : JSON.stringify(this.$route.query.pointList);
      list = JSON.parse(list);
      let array = [];
      list.forEach(el => {
        let obj = el;
        obj['left'] = el.coord.split(",")[0];
        obj['top'] = el.coord.split(",")[1];
        obj['lng'] = el.coord.split(",")[0];
        obj['lat'] = el.coord.split(",")[1];
        array.push(obj);
      });
      this.form.pointList = array;

      this.userCustomRoot = [
        {
          label: this.form.projectName,
          value: this.form.projectId,
          type: "1"
        }
      ];
      this.getSubentryList();
    },
    //页面初始化的一部分方法
    clearData() {
      this.nowPointId = "";
      this.showInputList = false;
      this.showImgPreview = false;
      this.inputList = [];
      this.unitList = [];
      this.subentryList = [];
      this.currentPointObj = {};
      this.tableList = [];
      this.scenePhotosList = [];
      this.copyUserList = [];
      this.$nextTick(() => {
        this.$refs["MapShow"].resetId();
      });
    },
    openImgLog(item, index) {
      this.imgIndex = index;
      this.showImgPreview = true;
    },
    //进入详情页
    goDetail() {
      this.$router.push({
        name: "TaskModeDetail",
        query: {
          id: this.form.id
        }
      });
    },
    //获取实测分项列表
    getSubentryList() {
      let params = {
        projectId: this.form.projectId
      };
      this.$A
        .Go("get", "/safety/measure/measureSubentryList", params)
        .then(res => {
          if (res.body && res.body.length) {
            this.subentryList = res.body;
            this.scrollBottom();
          } else {
            this.subentryList = [{ subentryName: "暂无数据", id: "" }];
          }
        });
    },
    //实测分项change事件
    subChange(val) {
      let params = {
        projectId: this.form.projectId,
        subentryId: val
      };
      this.$A
        .Go("get", "/safety/measure/measureContentList", params)
        .then(res => {
          if (res.body && res.body.length) {
            this.inputList = res.body;
            this.resetInput();
          } else {
            this.inputList = [];
          }
        });
    },
    scrollBottom() {
      this.$nextTick(() => {
        //this.$refs.$content.scrollTop = 300;
      });
    },
    //隐藏标号 swicth 切换
    FlagChange(val) {
      this.showPoint = !val;
    },
    //点击删除按钮
    delTrouble(index, tIndex) {
      this.tableList[index]["content"].splice(tIndex, 1);
      if (!this.tableList[index]["content"].length) {
        this.tableList.splice(index, 1);
      }
    },
    //删除图片deleteImg
    deleteImg(index) {
      this.scenePhotosList.splice(index, 1);
    },
    imgSuccess(list) {
      if (list.code == 200) {
        this.scenePhotosList.push(this.proUrl + list.body);
      }
    },
    //点击保存按钮
    savePointMessage() {
      var testList = [];
      this.inputList.forEach(item => {
        if (item.value || (item.value && item.value == 0)) {
          let obj = Object.assign({}, item);
          if (item.qualifiedType == 2) {
            obj.result = item.value;
          } else {
            if (
              Number(item.minValue) <= Number(item.value) &&
              Number(item.value) <= Number(item.maxValue)
            ) {
              obj.result = 1;
            } else {
              obj.result = 0;
            }
          }
          testList.push(obj);
        }
      });
      if (testList.length) {
        this.createTableList(testList);
      } else {
        this.$A.MS("请填写内容");
      }
    },
    //创造 tableList
    createTableList(testList) {
      //判断下面的tableList中有没有此点位以及实测分项的信息
      var sameIndex = this.tableList.findIndex(item => {
        return (
          item.pIndex == this.currentPointObj.pIndex &&
          item.subentryId == this.form.subentry
        );
      });
      if (sameIndex != -1) {
        //如果有 替换
        this.tableList[sameIndex].content = testList;
      } else {
        //如果没有  push
        this.tableList.push({
          point: this.currentPointObj.point,
          pIndex: this.currentPointObj.pIndex,
          subentryId: this.form.subentry,
          content: testList
        });
      }
    },
    //打开图片预览
    openFileLog(item) {
      this.fileUrl = item.url;
      this.showFileLog = true;
    },
    //关闭图片预览
    closeFileDialog() {
      this.showFileLog = false;
    },
    showSelectUser() {
      this.userOpen = true;
    },
    //人员选择
    userChange() {},
    delCopyUser(index) {
      this.copyUserList.splice(index, 1);
    },
    userConfirm(ev) {
      this.userOpen = false;
    },
    //点位的点击事件
    positionClick(data) {
      this.currentPointObj = {
        point: data.coord,
        pIndex: data.pIndex
      };
      //清空数据
      this.inputList.forEach(item => {
        if (item.value) {
          item.value = "";
        }
      });
      this.showInputList = true;
      this.scrollBottom();
      //回显数据
      this.resetInput();
    },
    resetInput() {
      this.$nextTick(() => {
        this.tableList.forEach(item => {
          if (
            item.pIndex == this.currentPointObj.pIndex &&
            item.subentryId == this.form.subentry
          ) {
            this.inputList.forEach((input, index) => {
              item.content.forEach(c => {
                if (input.id == c.id) {
                  this.$set(input, "value", c.value);
                }
              });
            });
          }
        });
        //this.$forceUpdate();
      });
    },
    validateForm() {
      try {
        if (!this.form.subentry) {
          this.$A.MS("请选择实测分项");
          throw new Error();
        }
        if (!this.tableList.length) {
          this.$A.MS("请录入实测内容");
          throw new Error();
        }
        // if (!(this.form.joinUser && this.form.joinUser.trim())) {
        //   this.$A.MS("请输入参与人");
        //   throw new Error();
        // }
        // if (!this.copyUserList.length) {
        //   this.$A.MS("请选择抄送人");
        //   throw new Error();
        // }
        // if (!this.scenePhotosList.length) {
        //   this.$A.MS("请选择现场图片");
        //   throw new Error();
        // }
      } catch (e) {
        return false;
      }
      return true;
    },
    submit() {
      console.log(this.validateForm());
      if (this.validateForm()) {
        this.$openLoading();
        let params = {
          projectId: this.form.projectId, //项目id
          areaId: this.form.areaId, //区域id
          taskId: this.form.id, //任务id
          deptId: this.form.deptId, //单位id
          joinUser: this.form.joinUser, //参与人
          url: this.scenePhotosList.join(","), //现场照片
          list: [
            //测量结果
          ]
        };
        let userList = [];
        this.copyUserList.forEach(item => {
          userList.push(item.value);
        });
        params.copyUser = userList;
        let list = [];
        this.tableList.forEach(tableItem => {
          let point = tableItem.point;
          tableItem.content.forEach(item => {
            list.push({
              projectId: this.form.projectId, //项目id
              areaId: this.form.areaId, //区域id
              taskId: this.form.id, //进行测量时所选的任务id（当为随机测量时值为空）
              contentId: item.id, //实测内容id(必填,contentId来自选择实测分项后加载出的实测内容主键id)
              content: item.contentName, //测量内容
              point: point, //测量点位坐标(必填)
              result: item.result, //测量结果，前端判断(0合格 1不合格)
              remark: item.conVal, //测量标准
              subentryId: item.subentryId, ////实测分项id(subentryId)
              value: item.value //测量值
            });
          });
        });
        params.list = list;
        this.$A.Go("post", "/safety/measure/add", params).then(res => {
          this.$closeLoading();
          if (res.code == 200) {
            this.$router.replace({
              name: "TaskModeSuccess",
              query: {
                id: res.body
              }
            });
          }
        });
      }
    }
  }
};
</script>

<style lang="scss">
#StartMeasure {
  .img-box {
    width: 0.75rem;
    height: 0.75rem;
    margin: 0 0.1rem;
    position: relative;
    img {
      height: 100%;
      width: 100%;
    }
    .close {
      position: absolute;
      height: 0.2rem;
      width: 0.2rem;
      line-height: 0.2rem;
      font-size: 0.15rem;
      top: 0.04rem;
      right: 0.04rem;
      color: #fff;
      border-radius: 50%;
      text-align: center;
      background-color: #ff4242;
    }
  }
}
</style>